import { Body, Controller, Delete, Get, Param, Post, Put, UsePipes } from '@nestjs/common';
import { DictionaryCategory } from 'src/entities/DictionaryCategory';
import { DictionaryCategoryModelService } from 'src/model/dictionary-category-model/dictionary-category-model.service';
import { DictionaryItemModelService } from 'src/model/dictionary-item-model/dictionary-item-model.service';
import dtoValidationPipe from 'src/pipe/Dto.pipe';
import { errorReturn, successReturn } from 'src/utils';
import { AddDto, EditDto } from './dto';

@Controller('dictionaryCategory')
export class DictionaryCategoryController {
    constructor(
        private model:DictionaryCategoryModelService,
        private itemModel:DictionaryItemModelService
    ){}

    @Get()
    async category() {
        return this.model.find()
    }

    @Post('add')
    @UsePipes(dtoValidationPipe())
    async add(@Body() dto:AddDto) {
        try {
            if((await this.model.isExistsByWhere({name : dto.name}))) return errorReturn('已存在相同的名称')
            if((await this.model.isExistsByWhere({code : dto.code}))) return errorReturn('已存在相同的编码')
            await this.model.insert(dto)
            return successReturn()
        } catch (error) {
            
        }

        return errorReturn()
    }

    @Put('edit/:id')
    @UsePipes(dtoValidationPipe({skipMissingProperties : true}))
    async edit(@Param('id') id:number, @Body() dto:EditDto) {
        try {
            const category = await this.model.findOne({id : id})
            if(!category) errorReturn()
            let updateData:{[key in keyof DictionaryCategory]? : DictionaryCategory[key]} = {}
            if(category.name != dto.name) {
                updateData.name = dto.name
            }
            if(category.code != dto.code) {
                updateData.code = dto.code
            }

            if((Object.keys(updateData)).length == 0) return successReturn()

            if(updateData.name && (await this.model.isExistsByWhere({name : dto.name}))) return errorReturn('已存在相同的名称')
            if(updateData.code && (await this.model.isExistsByWhere({code : dto.code}))) return errorReturn('已存在相同的编码')

            await this.model.update({id : id}, updateData)

            return successReturn()

        } catch (error) {
            
        }

        return errorReturn()
    }

    @Delete('delete/:id')
    async deleteCategory(@Param('id') id:number) {
        try {
            if((await this.itemModel.isExistsByWhere({categoryId : id}))) return errorReturn('该类目下存在分类，不可删除')
            await this.model.delete({id : id})
            return successReturn()
        } catch (error) {
            
        }
        return errorReturn()
    }
}
